<?php namespace Phpcmf\Controllers\Admin;

class Home extends \Phpcmf\Table
{

    private $spider;

    public function __construct(...$params) {
        parent::__construct(...$params);
        $this->spider = array_flip(\Phpcmf\Service::M('spider', 'spider')->spider);
        \Phpcmf\Service::V()->assign([
            'menu' => \Phpcmf\Service::M('auth')->_admin_menu(
                [
                    '蜘蛛记录' => [APP_DIR.'/'.\Phpcmf\Service::L('Router')->class.'/index', 'fa fa-bug'],
                    '分析统计' => [APP_DIR.'/'.\Phpcmf\Service::L('Router')->class.'/fenxi_index', 'fa fa-industry'],
                    '域名设置' => [APP_DIR.'/'.\Phpcmf\Service::L('Router')->class.'/edit', 'fa fa-cog'],
                    '代码安装' => [APP_DIR.'/'.\Phpcmf\Service::L('Router')->class.'/show', 'fa fa-code'],
                ]
            ),
            'spider' => $this->spider,
        ]);
    }

    public function index() {

        $field = [
            'title' => array(
                'ismain' => 1,
                'name' => dr_lang('标题'),
                'fieldname' => 'title',
                'fieldtype' => 'Text',
            ),
            'domain' => array(
                'ismain' => 1,
                'name' => dr_lang('域名'),
                'fieldname' => 'domain',
                'fieldtype' => 'Text',
            ),
            'url' => array(
                'ismain' => 1,
                'name' => dr_lang('地址'),
                'fieldname' => 'url',
                'fieldtype' => 'Text',
            ),
        ];

        $this->_init([
            'table' => 'app_spider',
            'field' => $field,
            'where_list' => 'site='.SITE_ID,
            'order_by' => 'inputtime desc',
        ]);

        $this->_List();

        \Phpcmf\Service::V()->assign([
            'field' => $field,
        ]);
        \Phpcmf\Service::V()->display('index.html');
    }


    public function fenxi_index() {

        $tid = intval($_GET['tid']);

        $date_to = dr_safe_replace($_GET['date_to']);
        $date_form = dr_safe_replace($_GET['date_form']);

        if ($date_to && $date_form) {
            $tid = 99;
            $stime = strtotime($date_form.' 00:00:00');
            $etime = strtotime($date_to.' 23:59:59');
        } else {
            switch ($tid) {

                case 2:
                    // 本周
                    $stime=mktime(0,0,0,date('m'),date('d')-date('w')+1,date('y'));
                    $etime=SYS_TIME;
                    break;
                case 1:
                    // 昨天的
                    $stime=mktime(0,0,0,date('m'),date('d')-1,date('Y'));
                    $etime=mktime(0,0,0,date('m'),date('d'),date('Y'))-1;
                    break;

                default:
                    // 今天的
                    $stime = mktime(0,0,0,date('m'),date('d'),date('Y'));
                    $etime = mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
                    break;
            }
        }



        $select = [
            0 => '今天',
            1 => '昨天',
            2 => '本周',
        ];

        $table = \Phpcmf\Service::M()->dbprefix('app_spider');

        // 统计蜘蛛
        $zzt = [
            'name' => [],
            'data' => [],
        ];
        $sql = 'SELECT spider,count(*) AS counts from `'.$table.'` where `site`='.SITE_ID.' and `inputtime` BETWEEN '.$stime.' AND '.$etime.' GROUP BY spider; ';
        $rows = \Phpcmf\Service::M()->db->query($sql)->getResultArray();
        if ($rows) {
            foreach ($rows as $t) {
                if ($this->spider[$t['spider']]) {
                    $zzt['name'][] = $this->spider[$t['spider']];
                    $zzt['data'][] = [
                        'value' => $t['counts'],
                        'name' => $this->spider[$t['spider']],
                    ];
                }
            }
        }
        $zzt['name'] = json_encode($zzt['name']);
        $zzt['data'] = json_encode($zzt['data']);

        // 时间段统计
        $sjd = [
            'name' => [
                '00:00',
                '04:00',
                '08:00',
                '12:00',
                '16:00',
                '20:00'
            ],
            'data' => [
                0,0,0,0,0,0
            ]
        ];
        $sql = 'SELECT
    COUNT(DISTINCT id) counts,
    FROM_UNIXTIME(
        inputtime,
        \'%H\'
    ) AS hours
FROM
    `'.$table.'`
WHERE  `site`='.SITE_ID.' and `inputtime` BETWEEN '.$stime.' AND '.$etime.' 
GROUP BY
    hours
ORDER BY inputtime';
        $rows = \Phpcmf\Service::M()->db->query($sql)->getResultArray();
        if ($rows) {
            foreach ($rows as $t) {
                if ($t['hours'] >= 0 && $t['hours'] < 4) {
                    $sjd['data'][0]+= (int)$t['counts'];
                } elseif ($t['hours'] >= 4 && $t['hours'] < 8) {
                    $sjd['data'][1]+= (int)$t['counts'];
                } elseif ($t['hours'] >= 8 && $t['hours'] < 12) {
                    $sjd['data'][2]+= (int)$t['counts'];
                } elseif ($t['hours'] >= 12 && $t['hours'] < 16) {
                    $sjd['data'][3]+= (int)$t['counts'];
                } elseif ($t['hours'] >= 16 && $t['hours'] < 20) {
                    $sjd['data'][4]+= (int)$t['counts'];
                } elseif ($t['hours'] >= 20) {
                    $sjd['data'][5]+= (int)$t['counts'];
                }
            }
        }
        $sjd['name'] = json_encode($sjd['name']);
        $sjd['data'] = json_encode($sjd['data']);

        // 按访问页面分组
        $sql = 'SELECT *,count(*) AS counts from `'.$table.'` where `site`='.SITE_ID.' and  `inputtime` BETWEEN '.$stime.' AND '.$etime.' GROUP BY url  order by counts desc limit 50; ';
        $rows = \Phpcmf\Service::M()->db->query($sql)->getResultArray();

        \Phpcmf\Service::V()->assign([
            'stime' => $stime,
            'etime' => $etime,
            'zzt' => $zzt,
            'sjd' => $sjd,
            'list' => $rows,
            'tid' => $tid,
            'select' => $select,
            'date_to' => $date_to,
            'date_form' => $date_form,
        ]);
        \Phpcmf\Service::V()->display('fenxi.html');
    }

    public function edit() {

        $domain = [];
        $myfile = WRITEPATH.'config/domain_spider.php';
        if (is_file($myfile)) {
            $domain = require $myfile;
        }

        if (IS_POST) {
            $domain = \Phpcmf\Service::L('input')->post('domain', true);
            if ($domain) {
                $domain = explode(PHP_EOL, $domain);
                file_put_contents(WRITEPATH.'config/domain_spider.php', '<?php return '.var_export($domain, true).';');
            }
            $this->_json(1, dr_lang('操作成功'));
        }

        $sys = [];
        $site = require WRITEPATH.'config/domain_site.php';
        foreach ($site as $i => $t) {
            $sys[] = $i;
        }

        \Phpcmf\Service::V()->assign([
            'sys' => $sys,
            'domain' => $domain,
        ]);
        \Phpcmf\Service::V()->display('domain.html');
    }

    public function show() {
        \Phpcmf\Service::V()->assign([
            'code' => '
<script language="JavaScript"> 
// 需要jquery的支持
$.ajax({
     type: "get",
     url: "'.SITE_URL.'index.php?s=spider&title="+document.title,
     dataType: "jsonp"
 });
</script>

            ',
        ]);
        \Phpcmf\Service::V()->display('code.html');
    }

    public function del() {
        $this->_init([
            'table' => 'app_spider',
        ]);
        $this->_Del(
            \Phpcmf\Service::L('Input')->get_post_ids(),
            null,
            null,
            \Phpcmf\Service::M()->dbprefix($this->init['table'])
        );
    }

}
